package com.ultrasoft.farmasoft.web;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ultrasoft.farmasoft.domain.Bill;
import com.ultrasoft.farmasoft.domain.Client;
import com.ultrasoft.farmasoft.domain.Dosage;
import com.ultrasoft.farmasoft.domain.Locality;
import com.ultrasoft.farmasoft.domain.Operation;
import com.ultrasoft.farmasoft.domain.Pharmacy;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Providerpharmacy;
import com.ultrasoft.farmasoft.domain.Region;
import com.ultrasoft.farmasoft.domain.Transaction;
import com.ultrasoft.farmasoft.domain.User;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.BuyProductsTransactionService;
import com.ultrasoft.farmasoft.service.ConfigServiceProducts;
import com.ultrasoft.farmasoft.service.OperationNationalTaxationService;
import com.ultrasoft.farmasoft.service.ProviderService;
import com.ultrasoft.farmasoft.service.ReportsService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;

@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/Operation")
public class OperationNationalTaxationController {
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	private final OperationNationalTaxationService operationNationalTaxationService;
	private final BuyProductsTransactionService buyProductsTransactionService; 
	
	@Autowired
	public OperationNationalTaxationController(BuyProductsTransactionService buyProductsTransactionService,OperationNationalTaxationService operationNationalTaxationService){
		this.operationNationalTaxationService 	= operationNationalTaxationService;
		this.buyProductsTransactionService		= buyProductsTransactionService;
	}
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	private String redirectNationalTaxation(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/nationalTaxation?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	private String handleNationalTaxation(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+
    				"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_)+
    				"&"+UtilCommon.optionId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.optionId_); 
		} catch (Exception e) {
			return redirectNationalTaxation(request);
		}
    }
	@RequestMapping(value="/nationalTaxation", method=RequestMethod.GET)
	public String handleRequestNationalTaxation(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			return UtilCommon.fOperation_NationalTaxation+"nationalTaxation";
		}else
			return redirectNationalTaxation(request);
	}
	@RequestMapping(value="/InvoiceDosage/invoiceDosage", method=RequestMethod.GET)
	public String handleRequestInvoiceDosage(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){		
			model.addAttribute("listDosage",operationNationalTaxationService.getListDosageByPharmacyIdOrderBy(s_pharmacyId));
			return UtilCommon.fOperation_NationalTaxation_InvoiceDosage+"invoiceDosage";
		}else
			return redirectNationalTaxation(request);
	}	
	@RequestMapping(value="/InvoiceDosage/invoiceDosageFormDosageNew", method=RequestMethod.GET)
	public String handleRequestInvoiceDosageFormDosageNew(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			model.addAttribute("dosage",new Dosage());
			return UtilCommon.fReferenceAdd+"formDosage";
		}else
			return redirectNationalTaxation(request);
	}	
	@RequestMapping(value = "/InvoiceDosage/invoiceDosageFormDosageNew", method = RequestMethod.POST)
   	public @ResponseBody Integer onSubmitRequestInvoiceDosageFormDosageNew(HttpServletRequest request){
		Integer temp = -1;
		List<Dosage> listDosage = operationNationalTaxationService.getListDosageByPharmacyIdOrderBy(s_pharmacyId);
		Dosage dosageTem = new Dosage(null);
		dosageTem.setDate(new Date());
		dosageTem.setNumOfPending(new BigInteger("0"));
		dosageTem.setOrderNumber(new BigInteger(UtilConverter.converterStringToString(request,"orderNumber")));
		dosageTem.setKey(UtilConverter.converterStringToString(request,"key"));
		dosageTem.setDeadline(UtilConverter.converterStringToDate(request,"deadline"));
		dosageTem.setStartNumBill(1);
		dosageTem.setEndNumBill(200);
		dosageTem.setLastNumBillIssued(1);
		dosageTem.setNit(s_UserPharmacy.getPharmacy().getNit());
		dosageTem.setIva(12.5);
		dosageTem.setIt(1.25);
		dosageTem.setPharmacyId(new Pharmacy(s_pharmacyId,s_UserPharmacy.getPharmacy().getName(),s_UserPharmacy.getPharmacy().getClient()));
		if(listDosage.isEmpty()){
			dosageTem.setState((short)1);	
			operationNationalTaxationService.addDosage(dosageTem);
		}else{
			Dosage d = listDosage.get(0);
			if(d.getState() == (short)2){
				dosageTem.setState((short)2);
				temp = 2;
			}else{
				if(d.getState() == (short)1){
					dosageTem.setState((short)2);
					operationNationalTaxationService.addDosage(dosageTem);
					temp = 1;
				}else
					if(d.getState() == (short)0){
						dosageTem.setState((short)1);
						operationNationalTaxationService.addDosage(dosageTem);
						temp = 0;
					}else
						temp = -2;
			}				
		}
		return temp;
    }
	@RequestMapping(value = "/InvoiceDosage/ajaxRemoveInvoiceDosage", method = RequestMethod.GET)
	public @ResponseBody String handleRequestAjAxRemoveInvoiceDosager(@RequestParam Integer dosageId){
		String temp = "No existe el elemento a eliminar";
		Dosage dosage = operationNationalTaxationService.searchDosageByDosageId(dosageId);
		if(dosage != null){
			operationNationalTaxationService.removeDosage(dosage);
			temp = "Se elimino Correctamente";
		}
		return temp;
    }	
	@RequestMapping(value="/InvoiceDosage/invoiceDosageFormDosageEdit", method=RequestMethod.GET)
	public String handleRequestInvoiceDosageFormDosageEdit(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			Dosage dosage = operationNationalTaxationService.searchDosageByDosageId(UtilConverter.converterStringToInteger(request,"_dosageId"));
			if(dosage != null)
				model.addAttribute("dosage",dosage);
			return UtilCommon.fReferenceAdd+"formDosage";
		}else
			return redirectNationalTaxation(request);
	}
	@RequestMapping(value = "/InvoiceDosage/invoiceDosageFormDosageEdit", method = RequestMethod.POST)
   	public @ResponseBody Integer onSubmitRequestInvoiceDosageFormDosageEdit(HttpServletRequest request){
		Integer temp = -1;
		Dosage dosage = operationNationalTaxationService.searchDosageByDosageId(UtilConverter.converterStringToInteger(request,"dosageId"));
		dosage.setDeadline(UtilConverter.converterStringToDate(request,"deadline"));
		dosage.setKey(UtilConverter.converterStringToString(request,"key"));
		dosage.setOrderNumber(new BigInteger(UtilConverter.converterStringToString(request,"orderNumber")));
		if(dosage != null){
			operationNationalTaxationService.updateDosage(dosage);
			temp = 1;
		}
		return temp;
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	@RequestMapping(value="/BookSales/bookSales", method=RequestMethod.GET)
	public String handleRequestBookSales(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	
			Date d = new Date();			
			Integer year = d.getYear();
			List<Integer> listYearTemp = new ArrayList<Integer>();
 			Integer tempPast = year-4;
			for (int i = tempPast; i <= year; i++) {
				listYearTemp.add(i+1900);
			}			
			String[] months = {"Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"};
			model.addAttribute("listMonths",months);
			model.addAttribute("listYear",listYearTemp);
			return UtilCommon.fOperation_NationalTaxation_BookSales+"bookSales";
		}else
			return redirectNationalTaxation(request);
	}
	/*
	@RequestMapping(value = "/BookSales/bookSalesByGestionByPeriod", method = RequestMethod.GET)
   	public @ResponseBody List<Bill> onSubmitRequestBookSalesByGestionByPeriod(HttpServletRequest request){
		List<Bill> listBill = new ArrayList<Bill>();
		Integer year = UtilConverter.converterStringToInteger(request,"year");
		Integer month = UtilConverter.converterStringToInteger(request,"month");
		
		Date dateStart = new Date((year-1900),month,1);
		
		Calendar tempStartDate = Calendar.getInstance();
        Calendar tempEndDate = Calendar.getInstance();
        tempStartDate.setTime(dateStart);
        tempEndDate.setTime(dateStart);
        tempEndDate.add(Calendar.MONTH,1);
        
		List<Transaction> tempListTransaction = buyProductsTransactionService.getListTransactionByPharmacyIdByStartDateByEndDate(s_pharmacyId,tempStartDate.getTime(),tempEndDate.getTime());
		for (Transaction transaction : tempListTransaction) {
			listBill.add(getTransactionTemp(transaction).getBill());
		}		
		return listBill;
    }
	*/
	
	
	@RequestMapping(value = "/BookSales/bookSalesByGestionByPeriod", method = RequestMethod.GET)
   	public @ResponseBody List<Transaction> onSubmitRequestBookSalesByGestionByPeriod(HttpServletRequest request){
		List<Transaction> listTransaction = new ArrayList<Transaction>();
		Integer year = UtilConverter.converterStringToInteger(request,"year");
		Integer month = UtilConverter.converterStringToInteger(request,"month");
		
		Date dateStart = new Date((year-1900),month,1);
		
		Calendar tempStartDate = Calendar.getInstance();
        Calendar tempEndDate = Calendar.getInstance();
        tempStartDate.setTime(dateStart);
        tempEndDate.setTime(dateStart);
        tempEndDate.add(Calendar.MONTH,1);
        
		List<Transaction> tempListTransaction = buyProductsTransactionService.getListTransactionByPharmacyIdByStartDateByEndDate(s_pharmacyId,tempStartDate.getTime(),tempEndDate.getTime());
		for (Transaction transaction : tempListTransaction) {
			listTransaction.add(getTransactionTemp(transaction));
		}		
		return listTransaction;
    }
	
	private Transaction getTransactionTemp(Transaction transaction){
		Transaction t = new Transaction(transaction.getTransactionPK().getPeriodIds(),transaction.getTransactionPK().getTransactionId());
		t.setAmount(transaction.getAmount());
		t.setUnits(transaction.getUnits());
		t.setDateTransaction(new Date(transaction.getDateTransaction().getTime()));
		if(transaction.getOperationId() != null){
			Operation o = new Operation(transaction.getOperationId().getOperationId(),transaction.getOperationId().getName());
			t.setOperationId(o);
		}
		if(transaction.getClientId() != null){
			Pharmacy pharma = new Pharmacy(transaction.getClientId().getPharmacyId().getPharmacyId(),transaction.getClientId().getPharmacyId().getName(),transaction.getClientId().getPharmacyId().getClient());
			Client c = new Client(transaction.getClientId().getClientId(),transaction.getClientId().getClientType(),transaction.getClientId().getName(),transaction.getClientId().getActive());
			c.setNit(transaction.getClientId().getNit());
			c.setPharmacyId(pharma);
			t.setClientId(c);
		}
		if(transaction.getUserpharmacy() != null){
			Userpharmacy up = new Userpharmacy(transaction.getUserpharmacy().getUserpharmacyPK().getPharmacyId(),transaction.getUserpharmacy().getUserpharmacyPK().getUserId(),transaction.getUserpharmacy().getActive());
			if(transaction.getUserpharmacy().getPharmacy() != null){
				Pharmacy pharma = new Pharmacy(transaction.getUserpharmacy().getPharmacy().getPharmacyId(),transaction.getUserpharmacy().getPharmacy().getName(),transaction.getUserpharmacy().getPharmacy().getClient());
				if(transaction.getUserpharmacy().getPharmacy().getLocality() != null){
					Locality locality = new Locality(transaction.getUserpharmacy().getPharmacy().getLocality().getLocalityPK().getRegionId(),transaction.getUserpharmacy().getPharmacy().getLocality().getLocalityPK().getLocalityId());
					locality.setName(transaction.getUserpharmacy().getPharmacy().getLocality().getName());
					if(transaction.getUserpharmacy().getPharmacy().getLocality().getRegion() != null){
						Region r = new Region(transaction.getUserpharmacy().getPharmacy().getLocality().getRegion().getRegionId());
						r.setName(transaction.getUserpharmacy().getPharmacy().getLocality().getRegion().getName());
						locality.setRegion(r);
					}					
					pharma.setLocality(locality);
				}
				up.setPharmacy(pharma);
			}
			if(transaction.getUserpharmacy().getUser() != null){
				User u = new User(transaction.getUserpharmacy().getUser().getUserId());
				u.setName(transaction.getUserpharmacy().getUser().getName());
				u.setLastName(transaction.getUserpharmacy().getUser().getLastName());
				u.setLastName2(transaction.getUserpharmacy().getUser().getLastName2());
				u.setCi(transaction.getUserpharmacy().getUser().getCi());
				up.setUser(u);
			}
			t.setUserpharmacy(up);
		}
		if(transaction.getBill() != null){
			Dosage dosage = new Dosage(transaction.getBill().getDosageId().getDosageId(),transaction.getBill().getDosageId().getDate(),transaction.getBill().getDosageId().getNumOfPending(),transaction.getBill().getDosageId().getOrderNumber(),transaction.getBill().getDosageId().getKey(),transaction.getBill().getDosageId().getDeadline(),transaction.getBill().getDosageId().getStartNumBill(),transaction.getBill().getDosageId().getEndNumBill(),transaction.getBill().getDosageId().getLastNumBillIssued(),transaction.getBill().getDosageId().getNit(),transaction.getBill().getDosageId().getIva(),transaction.getBill().getDosageId().getIt(),transaction.getBill().getDosageId().getState());
			
			Bill b = new Bill(transaction.getBill().getBillPK().getPeriodId(),transaction.getBill().getBillPK().getBillId());
			b.setDate(transaction.getBill().getDate());
			b.setClient(transaction.getBill().getClient());
			b.setBillNum(transaction.getBill().getBillNum());
			b.setNit(transaction.getBill().getNit());
			b.setAmount(transaction.getBill().getAmount());
			b.setControlCode(transaction.getBill().getControlCode());
			b.setActive(transaction.getBill().getActive());
			b.setDosageId(dosage);
			t.setBill(b);
		}
		//Bill b = new Bill(transaction.getBill().getBillPK().getPeriodId(),transaction.getBill().getBillPK().getBillId());
		//b.set
		return t;
	}
}
